<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>网格可视化工具</title>
    <!-- 引入Leaflet CSS -->
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
    <!-- 引入Leaflet JS -->
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    <!-- 引入Turf.js用于地理计算 -->
    <script src="https://unpkg.com/@turf/turf@6.5.0/turf.min.js"></script>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: Arial, sans-serif;
            display: flex;
            flex-direction: column;
            height: 100vh;
        }
        .header {
            padding: 10px 20px;
            background-color: #f8f9fa;
            border-bottom: 1px solid #dee2e6;
            display: flex;
            align-items: center;
            gap: 15px;
        }
        .header h1 {
            margin: 0;
            font-size: 24px;
            color: #333;
        }
        .controls {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        .control-group {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }
        .control-group label {
            font-size: 14px;
            color: #666;
        }
        select, button {
            padding: 8px 12px;
            border: 1px solid #ced4da;
            border-radius: 4px;
            font-size: 14px;
        }
        button {
            background-color: #007bff;
            color: white;
            cursor: pointer;
            border: none;
        }
        button:hover {
            background-color: #0056b3;
        }
        .map-container {
            flex: 1;
            position: relative;
        }
        #map {
            width: 100%;
            height: 100%;
        }
        .info-panel {
            position: absolute;
            bottom: 20px;
            right: 20px;
            background: white;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            max-width: 300px;
            z-index: 1000;
        }
        .info-panel h3 {
            margin-top: 0;
            margin-bottom: 10px;
            color: #333;
            font-size: 18px;
        }
        .info-panel p {
            margin: 5px 0;
            font-size: 14px;
            color: #666;
        }
        .highlight {
            background-color: #fff3cd;
            padding: 2px 5px;
            border-radius: 3px;
            font-weight: bold;
        }
        .legend {
            position: absolute;
            top: 100px;
            right: 20px;
            background: white;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            z-index: 1000;
        }
        .legend-item {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
        }
        .legend-color {
            width: 20px;
            height: 20px;
            margin-right: 8px;
            border: 1px solid #ddd;
        }
        .city-boundary {
            fill: none;
            stroke: #dc3545;
            stroke-width: 2px;
        }
        .grid-cell {
            fill: rgba(0, 123, 255, 0.1);
            stroke: #007bff;
            stroke-width: 1px;
        }
        .grid-cell:hover {
            fill: rgba(0, 123, 255, 0.3);
            stroke-width: 2px;
        }
        .selected-grid {
            fill: rgba(255, 193, 7, 0.4);
            stroke: #ffc107;
            stroke-width: 3px;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>网格可视化工具</h1>
        <div class="controls">
            <div class="control-group">
                <label for="city-select">选择城市：</label>
                <select id="city-select"></select>
            </div>
            <div class="control-group">
                <label for="grid-density">网格密度：</label>
                <select id="grid-density">
                    <option value="all">显示全部网格</option>
                    <option value="quarter" selected>显示1/4网格（推荐）</option>
                    <option value="tenth">显示1/10网格</option>
                </select>
            </div>
            <button id="zoom-to-city">缩放到城市</button>
            <button id="toggle-grid">切换网格显示</button>
            <button id="toggle-boundary">切换边界显示</button>
        </div>
    </div>
    
    <div class="map-container">
        <div id="map"></div>
        
        <div class="legend">
            <h4>图例</h4>
            <div class="legend-item">
                <div class="legend-color" style="background: transparent; border: 2px solid #dc3545;"></div>
                <span>城市边界</span>
            </div>
            <div class="legend-item">
                <div class="legend-color" style="background: rgba(0, 123, 255, 0.1); border: 1px solid #007bff;"></div>
                <span>4km×4km网格</span>
            </div>
            <div class="legend-item">
                <div class="legend-color" style="background: rgba(255, 193, 7, 0.4); border: 3px solid #ffc107;"></div>
                <span>选中网格</span>
            </div>
        </div>
        
        <div class="info-panel">
            <h3>网格信息</h3>
            <p><strong>当前城市：</strong><span id="current-city">未选择</span></p>
            <p><strong>网格总数：</strong><span id="total-grids">0</span></p>
            <p><strong>当前显示：</strong><span id="displayed-grids">0</span></p>
            <p id="grid-info" style="display: none;">
                <strong>选中网格：</strong><br>
                <span id="grid-bbox"></span>
            </p>
        </div>
    </div>

    <script>
        // 全局变量
        let map;
        let gridData = null;
        let cityLayer;
        let gridLayer;
        let selectedCity = null;
        let selectedGrid = null;
        let gridVisible = true;
        let boundaryVisible = true;

        // 初始化地图
        function initMap() {
            try {
                // 创建地图实例
                map = L.map('map').setView([32.0, 119.0], 7); // 江苏中部位置
                
                // 添加底图
                L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
                }).addTo(map);
                
                // 创建并添加图层组
                cityLayer = L.layerGroup().addTo(map);
                gridLayer = L.layerGroup().addTo(map);
                
                console.log('地图初始化成功');
                
                // 加载网格数据
                loadGridData();
                
                // 绑定事件
                document.getElementById('city-select').addEventListener('change', onCityChange);
                document.getElementById('zoom-to-city').addEventListener('click', zoomToCity);
                document.getElementById('toggle-grid').addEventListener('click', toggleGrid);
                document.getElementById('toggle-boundary').addEventListener('click', toggleBoundary);
                document.getElementById('grid-density').addEventListener('change', onDensityChange);
            } catch (error) {
                console.error('地图初始化失败:', error);
                alert('地图初始化失败，请检查浏览器控制台获取详细信息');
            }
        }

        // 加载网格数据
        function loadGridData() {
            try {
                console.log('开始加载网格数据...');
                fetch('grid_results.json')
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('HTTP错误，状态码: ' + response.status);
                        }
                        return response.json();
                    })
                    .then(data => {
                        console.log('网格数据加载成功，共', Object.keys(data).length, '个城市');
                        gridData = data;
                        populateCitySelect();
                        
                        // 默认显示第一个城市
                        if (Object.keys(data).length > 0) {
                            const firstCity = Object.keys(data)[0];
                            document.getElementById('city-select').value = firstCity;
                            onCityChange();
                        }
                    })
                    .catch(error => {
                        console.error('加载网格数据失败:', error);
                        alert('加载网格数据失败: ' + error.message + '\n请确认grid_results.json文件是否存在于同一目录中');
                    });
            } catch (error) {
                console.error('loadGridData函数错误:', error);
                alert('数据加载函数执行出错');
            }
        }

        // 填充城市选择下拉框
        function populateCitySelect() {
            try {
                console.log('开始填充城市选择框，数据结构类型:', Array.isArray(gridData) ? '数组' : '对象');
                const select = document.getElementById('city-select');
                select.innerHTML = '<option value="">请选择城市</option>';
                
                // 处理不同的数据结构
                if (Array.isArray(gridData)) {
                    // 如果是数组格式
                    gridData.forEach((cityItem, index) => {
                        const cityName = cityItem.cityName || `城市${index + 1}`;
                        const option = document.createElement('option');
                        option.value = cityName;
                        option.textContent = cityName;
                        select.appendChild(option);
                    });
                } else if (typeof gridData === 'object' && gridData !== null) {
                    // 如果是对象格式
                    Object.entries(gridData).forEach(([key, value]) => {
                        const cityName = value.cityName || key;
                        const option = document.createElement('option');
                        option.value = key;
                        option.textContent = cityName;
                        select.appendChild(option);
                    });
                }
                
                console.log('城市选择框填充完成，共', select.options.length - 1, '个城市');
            } catch (error) {
                console.error('填充城市选择框失败:', error);
                alert('填充城市列表失败');
            }
        }

        // 格式化城市名称
        function formatCityName(cityCode) {
            // 移除geo后缀，首字母大写
            let name = cityCode.replace('geo', '');
            return name.charAt(0).toUpperCase() + name.slice(1);
        }

        // 城市选择变化事件
        function onCityChange() {
            try {
                const selectedValue = this.value;
                console.log('选择城市:', selectedValue);
                
                if (!selectedValue) return;
                
                let cityData;
                // 处理不同的数据结构
                if (Array.isArray(gridData)) {
                    // 数组格式：查找匹配的城市
                    cityData = gridData.find(item => item.cityName === selectedValue);
                } else if (typeof gridData === 'object' && gridData !== null) {
                    // 对象格式：直接获取
                    cityData = gridData[selectedValue];
                }
                
                if (cityData) {
                    selectedCity = selectedValue;
                    selectedGrid = null;
                    console.log('找到城市数据，网格数量:', cityData.grids ? cityData.grids.length : '未知');
                    updateInfoPanel();
                    drawCityAndGrids();
                } else {
                    console.warn('未找到城市数据:', selectedValue);
                    alert('未找到该城市的数据');
                }
            } catch (error) {
                console.error('城市选择处理失败:', error);
                alert('处理城市选择时出错');
            }
        }

        // 密度变化事件
        function onDensityChange() {
            if (selectedCity) {
                drawCityAndGrids();
            }
        }

        // 绘制城市边界和网格
        function drawCityAndGrids() {
            try {
                // 清空现有图层
                cityLayer.clearLayers();
                gridLayer.clearLayers();
                
                let cityData;
                // 处理不同的数据结构
                if (Array.isArray(gridData)) {
                    cityData = gridData.find(item => item.cityName === selectedCity);
                } else if (typeof gridData === 'object' && gridData !== null) {
                    cityData = gridData[selectedCity];
                }
                
                if (!cityData || !cityData.grids) {
                    console.error('城市数据不完整或不存在');
                    alert('该城市数据不完整或不存在');
                    return;
                }
                
                console.log('开始绘制城市边界和网格...');
            
            const bbox = cityData.originalBBox;
            
            // 绘制城市边界（使用边界框表示）
            if (boundaryVisible) {
                const boundaryPolygon = turf.bboxPolygon(bbox);
                const boundaryLayer = L.geoJSON(boundaryPolygon, {
                    style: {
                        fillOpacity: 0,
                        stroke: true,
                        color: '#dc3545',
                        weight: 2
                    }
                }).addTo(cityLayer);
            }
            
            // 绘制网格
            if (gridVisible) {
                const grids = cityData.grids;
                const density = document.getElementById('grid-density').value;
                
                let gridsToShow = grids;
                if (density === 'quarter') {
                    // 显示1/4的网格
                    gridsToShow = grids.filter((_, index) => index % 4 === 0);
                } else if (density === 'tenth') {
                    // 显示1/10的网格
                    gridsToShow = grids.filter((_, index) => index % 10 === 0);
                }
                
                // 更新显示的网格数量
                document.getElementById('displayed-grids').textContent = gridsToShow.length;
                
                // 为每个网格创建GeoJSON多边形并添加到地图
                gridsToShow.forEach((gridBBox, index) => {
                    const gridPolygon = turf.bboxPolygon(gridBBox);
                    const gridFeature = L.geoJSON(gridPolygon, {
                        style: {
                            fillOpacity: 0.1,
                            fillColor: '#007bff',
                            stroke: true,
                            color: '#007bff',
                            weight: 1
                        },
                        onEachFeature: (feature, layer) => {
                            // 绑定点击事件
                            layer.on('click', () => {
                                // 移除之前选中的网格样式
                                if (selectedGrid) {
                                    selectedGrid.setStyle({
                                        fillOpacity: 0.1,
                                        fillColor: '#007bff',
                                        stroke: true,
                                        color: '#007bff',
                                        weight: 1
                                    });
                                }
                                
                                // 设置新选中的网格样式
                                layer.setStyle({
                                    fillOpacity: 0.4,
                                    fillColor: '#ffc107',
                                    stroke: true,
                                    color: '#ffc107',
                                    weight: 3
                                });
                                
                                selectedGrid = layer;
                                updateGridInfo(gridBBox);
                            });
                            
                            // 添加鼠标悬停提示
                            layer.bindTooltip(`网格索引: ${index}`);
                        }
                    }).addTo(gridLayer);
                });
            }
            } catch (error) {
                console.error('绘制城市和网格失败:', error);
                alert('绘制地图时出错');
            }
        }

        // 更新信息面板
        function updateInfoPanel() {
            if (selectedCity && gridData[selectedCity]) {
                const cityData = gridData[selectedCity];
                document.getElementById('current-city').textContent = formatCityName(selectedCity);
                document.getElementById('total-grids').textContent = cityData.gridCount || 0;
                
                // 重置网格信息
                document.getElementById('grid-info').style.display = 'none';
                
                // 如果有网格数据，显示当前密度下显示的网格数量
                if (cityData.grids) {
                    const density = document.getElementById('grid-density').value;
                    let displayedCount = cityData.grids.length;
                    
                    if (density === 'quarter') {
                        displayedCount = Math.ceil(cityData.grids.length / 4);
                    } else if (density === 'tenth') {
                        displayedCount = Math.ceil(cityData.grids.length / 10);
                    }
                    
                    document.getElementById('displayed-grids').textContent = displayedCount;
                }
            }
        }

        // 更新网格信息
        function updateGridInfo(gridBBox) {
            const gridInfoEl = document.getElementById('grid-info');
            const gridBBoxEl = document.getElementById('grid-bbox');
            
            // 格式化边界框信息
            const formattedBBox = `[${gridBBox[0].toFixed(6)}, ${gridBBox[1].toFixed(6)}, ${gridBBox[2].toFixed(6)}, ${gridBBox[3].toFixed(6)}]`;
            gridBBoxEl.textContent = formattedBBox;
            
            gridInfoEl.style.display = 'block';
        }

        // 缩放到选中的城市
        function zoomToCity() {
            if (selectedCity && gridData[selectedCity]) {
                const bbox = gridData[selectedCity].originalBBox;
                if (bbox) {
                    // 创建边界框的LatLngBounds对象
                    const southWest = L.latLng(bbox[1], bbox[0]);
                    const northEast = L.latLng(bbox[3], bbox[2]);
                    const bounds = L.latLngBounds(southWest, northEast);
                    
                    // 缩放到边界框，添加一些边距
                    map.fitBounds(bounds, { padding: [50, 50] });
                }
            } else {
                alert('请先选择一个城市');
            }
        }

        // 切换网格显示
        function toggleGrid() {
            gridVisible = !gridVisible;
            
            if (gridVisible) {
                map.addLayer(gridLayer);
                this.textContent = '隐藏网格';
                if (selectedCity) {
                    drawCityAndGrids();
                }
            } else {
                map.removeLayer(gridLayer);
                this.textContent = '显示网格';
                document.getElementById('displayed-grids').textContent = 0;
            }
        }

        // 切换边界显示
        function toggleBoundary() {
            boundaryVisible = !boundaryVisible;
            
            if (boundaryVisible) {
                map.addLayer(cityLayer);
                this.textContent = '隐藏边界';
                if (selectedCity) {
                    drawCityAndGrids();
                }
            } else {
                map.removeLayer(cityLayer);
                this.textContent = '显示边界';
            }
        }

        // 页面加载完成后初始化地图
        window.onload = initMap;
    </script>
</body>
</html>